package com.bxd.baodan.activity;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.adapter.CommonAdapter;
import com.bxd.baodan.adapter.ViewHolder;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.item.InsuranceTypeBean;
import com.bxd.baodan.item.UploadImageBean;
import com.bxd.baodan.util.AppManager;
import com.bxd.baodan.util.CommomDialog;
import com.bxd.baodan.util.GlideUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.widget.IosDialog;
import com.bxd.baodan.widget.MyListView;
import com.bxd.baodan.widget.MyRadioGroup;
import com.umeng.analytics.MobclickAgent;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class AlbumAddActivity extends BaseActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_CHOOSE = 2;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 3;// 结果



    private TextView mTvCancel;
    private MyRadioGroup mMyRadioGroup;
    private RadioGroup mRadioGroup1;
    private String insuranceType;
    private String needEvaluation="1";
    private List<String> photoList = new ArrayList<>();
    private List<String> urlList = new ArrayList<>();
    private MyListView lv;

    CommonAdapter<String> mCommonAdapter;
    private ImageView mIvAddImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_album_add);
        hideBar();
        initView();
        clearPhoto(new File(getPath()));
        gallery();
        initInsuranceType();
    }

    private void initView() {
        mTvCancel = getTextView(R.id.tv_cancel);
        mTvCancel.setOnClickListener(this);

        lv = (MyListView) findViewById(R.id.lv);
        mIvAddImage = getImageView(R.id.iv_add_image);

        getRelativeLayout(R.id.rl_next).setOnClickListener(this);

        mMyRadioGroup = (MyRadioGroup) findViewById(R.id.radio_group);
        mRadioGroup1 = (RadioGroup) findViewById(R.id.radio_group1);


        mIvAddImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                gallery();
            }
        });

        mMyRadioGroup.setOnCheckedChangeListener(new MyRadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(MyRadioGroup group, int checkedId) {
                if (mData == null || mData.size() == 0) {
                    return;
                }
                switch (checkedId) {
                    case R.id.radio_button_1:
                        insuranceType = mData.get(0).getId();
                        break;
                    case R.id.radio_button_2:
                        insuranceType = mData.get(1).getId();
                        break;
                    case R.id.radio_button_3:
                        insuranceType = mData.get(2).getId();
                        break;
                    case R.id.radio_button_4:
                        insuranceType = mData.get(3).getId();
                        break;
                    case R.id.radio_button_5:
                        insuranceType = mData.get(4).getId();
                        break;
                    case R.id.radio_button_6:
                        insuranceType = mData.get(5).getId();
                        break;
                }
            }
        });

        mRadioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.radio_button_1_1:
                        MobclickAgent.onEvent(App.getContext(), "v6_0_0_SY_bdcp_xycp");
                        needEvaluation = "1";
                        break;
                    case R.id.radio_button_1_2:
                        needEvaluation = "0";
                        break;
                }
            }
        });


        mCommonAdapter = new CommonAdapter<String>(this, urlList, R.layout.baodan_item) {
            @Override
            public void convert(final ViewHolder holder, final String item) {

                GlideUtil.loadImage(AlbumAddActivity.this, item, (ImageView) holder.getView(R.id.iv));
                holder.getView(R.id.del).setVisibility(View.VISIBLE);
                holder.getView(R.id.del).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            urlList.remove(item);
                            photoList.remove(holder.getPosition());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        notifyChanged();
                    }
                });
            }
        };


        lv.setAdapter(mCommonAdapter);
        notifyChanged();
    }


    public void notifyChanged() {
        if (urlList.size() <2) {
            mIvAddImage.setVisibility(View.VISIBLE);
        } else {
            mIvAddImage.setVisibility(View.GONE);
        }
        mCommonAdapter.notifyDataSetChanged();


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {


            case R.id.tv_cancel:
                back();
                break;
            case R.id.rl_next:
                // 保存
                if (TextUtils.isEmpty(insuranceType)) {
                    showToast("请选择保险类型！");
                    return;
                }


                if (TextUtils.isEmpty(needEvaluation)) {
                    showToast("请选择是否需要精算师为您做保单测评！");
                    return;
                }

                NetUtil netUtil = new NetUtil(AlbumAddActivity.this, JsonApi.INSURANCE_ADD);
                String fileStr;
                if (photoList != null && photoList.size() == 1) {
                    fileStr = photoList.get(0);
                } else if (photoList != null && photoList.size() == 2) {
                    fileStr = photoList.get(0) + "," + photoList.get(1);
                } else {
                    showToast("照片上传不成功");
                    return;
                }

                netUtil.setParams("catId", insuranceType);
                netUtil.setParams("file", fileStr);
                netUtil.setParams("needEvaluation", needEvaluation);
                netUtil.setParams("processWay ", "2");

                netUtil.postRequest("正在保存数据...", new NetUtil.RequestStringListener() {
                    @Override
                    public void onComplete(String result) {

                        photoList.clear();
                        showExitDialog("保单上传成功!",
                                "规划顾问正在为保单评测~");

                    }
                });
                break;
        }
    }

    /**
     * 从相册获取
     */
    public void gallery() {

        Matisse.from(AlbumAddActivity.this)
                .choose(MimeType.ofAll(), false)
                .countable(true)
                .capture(true)
                .captureStrategy(
                        new CaptureStrategy(true, "com.bxd.baodan.fileprovider"))
                .maxSelectable(2 - photoList.size())
                .gridExpectedSize(
                        getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(REQUEST_CODE_CHOOSE);

    }


    /**
     * 剪切图片
     */
    private void crop(Uri uri) {
        // 裁剪图片意图
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        // 裁剪框的比例，1：1
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // 裁剪后输出图片的尺寸大小
        intent.putExtra("outputX", 250);
        intent.putExtra("outputY", 250);
        // 图片格式
        intent.putExtra("outputFormat", "JPEG");
        intent.putExtra("noFaceDetection", true);// 取消人脸识别
        intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }


    private List<InsuranceTypeBean.ListBean> mData;

    private void initInsuranceType() {
        NetUtil netUtil = new NetUtil(this, JsonApi.INSURANCE_CATEGORY);
        netUtil.postRequest("正在加载数据...", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {
                InsuranceTypeBean mBean = new Gson().fromJson(JSONUtil.getData(result),
                        new TypeToken<InsuranceTypeBean>() {
                        }.getType());
                mData = mBean.getList();
                showRadioButton(mData);
            }
        });
    }

    private void showRadioButton(List<InsuranceTypeBean.ListBean> data) {
        if (data == null || data.size() == 0) {
            return;
        }
        RadioButton button1 = (RadioButton) mMyRadioGroup.findViewById(R.id.radio_button_1);
        RadioButton button2 = (RadioButton) mMyRadioGroup.findViewById(R.id.radio_button_2);
        RadioButton button3 = (RadioButton) mMyRadioGroup.findViewById(R.id.radio_button_3);
        RadioButton button4 = (RadioButton) mMyRadioGroup.findViewById(R.id.radio_button_4);
        RadioButton button5 = (RadioButton) mMyRadioGroup.findViewById(R.id.radio_button_5);
        RadioButton button6 = (RadioButton) mMyRadioGroup.findViewById(R.id.radio_button_6);

        button1.setVisibility(View.VISIBLE);
        button2.setVisibility(View.VISIBLE);
        button3.setVisibility(View.VISIBLE);
        button4.setVisibility(View.VISIBLE);
        button5.setVisibility(View.VISIBLE);
        button6.setVisibility(View.VISIBLE);

        if (!TextUtils.isEmpty(data.get(0).getName())) {
            button1.setText(data.get(0).getName());
        }
        if (!TextUtils.isEmpty(data.get(1).getName())) {
            button2.setText(data.get(1).getName());
        }
        if (!TextUtils.isEmpty(data.get(2).getName())) {
            button3.setText(data.get(2).getName());
        }
        if (!TextUtils.isEmpty(data.get(3).getName())) {
            button4.setText(data.get(3).getName());
        }
        if (!TextUtils.isEmpty(data.get(4).getName())) {
            button5.setText(data.get(4).getName());
        }
        if (!TextUtils.isEmpty(data.get(5).getName())) {
            button6.setText(data.get(5).getName());
        }

        if (data.size() < 6) {
            mMyRadioGroup.findViewById(R.id.radio_button_6).setVisibility(View.INVISIBLE);
        }
        if (data.size() < 5) {
            mMyRadioGroup.findViewById(R.id.radio_button_5).setVisibility(View.INVISIBLE);
        }
        if (data.size() < 4) {
            mMyRadioGroup.findViewById(R.id.radio_button_4).setVisibility(View.INVISIBLE);
        }
        if (data.size() < 3) {
            mMyRadioGroup.findViewById(R.id.radio_button_3).setVisibility(View.INVISIBLE);
        }
        if (data.size() < 2) {
            mMyRadioGroup.findViewById(R.id.radio_button_2).setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 上传图片
     */
    private void uploadImage(File file) {

        NetUtil netUtil = new NetUtil(this, JsonApi.UPLOAD_IMAGE);
        netUtil.setFile("file", file);
        netUtil.postFile("图片上传中", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {

                UploadImageBean mBean = new Gson().fromJson(JSONUtil.getData(result),
                        new TypeToken<UploadImageBean>() {
                        }.getType());
                photoList.add(mBean.file);
            }
        });
    }


    /**
     * 退出
     */
    private void back() {
        new CommomDialog(AlbumAddActivity.this, R.style.insurance_dialog, "确认退出添加保单？", new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    dialog.dismiss();
                    AlbumAddActivity.this.finish();
                }
            }
        }).setTitle("退出添加").show();
    }

    @Override
    public void onBackPressed() {
        back();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {


        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {


            compressWithLs(Matisse.obtainPathResult(data));
            urlList.addAll( Matisse.obtainPathResult(data));
            notifyChanged();
        }

    }
    /**
     * 压缩图片 Listener 方式
     */
    private void compressWithLs(final List<String> photos) {

        Luban.with(this)
                .load(photos)
                .ignoreBy(100)
                .setTargetDir(getPath())
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        uploadImage(file);
                    }

                    @Override
                    public void onError(Throwable e) {
                    }
                }).launch();
    }


    public void clearPhoto(File file) {

        if (file.isFile()) {
            file.delete();
            return;
        }
        if (file.isDirectory()) {
            File[] childFile = file.listFiles();
            if (childFile == null || childFile.length == 0) {
                file.delete();
                return;
            }
            for (File f : childFile) {
                clearPhoto(f);
            }
            file.delete();
        }
    }
    private String getPath() {
        String path = Environment.getExternalStorageDirectory() + "/bxd/image/";
        File file = new File(path);
        if (file.mkdirs()) {
            return path;
        }
        return path;
    }

    public void showExitDialog(String title, String content) {
        new IosDialog(this).builder().setCancelable(false)
                .setTitle(title)
                .setMsg(content)
                .setNegativeButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AppManager.getInstance().finishOtherActivity(MainActivity.class);
                     //  finish();
                    }
                }).show();
    }
}
